package cloud.pangui.core.mongo.element;

import org.bson.Document;

/**
 * 聚合函数类
 * @Auther hepangui
 * @Date 2020/10/06 0001
*/
public class Aggr extends Func {

	/**
	 * 求和
	 */
	public static final String SUM = "$sum";

	/**
	 * 求平均
	 */
	public static final String AVG = "$avg";

	/**
	 * 最小值
	 */
	public static final String MIN = "$min";

	/**
	 * 最大值
	 */
	public static final String MAX = "$max";

	/**
	 * 第一个
	 */
	public static final String FIRST = "$first";

	/**
	 * 最后一个
	 */
	public static final String LAST = "$last";


	private Aggr(String key, String symbol) {
		this.doc = new Document(symbol, "$" + key);
	}

	private Aggr(Ele key, String symbol) {
		this.doc = new Document(symbol, key.toExpression());
	}

	private Aggr() {
	}

	/**
	 * 最大值
	 *
	 * @param key
	 * @return
	 */
	public static Aggr max(String key) {
		return new Aggr(key, MAX);
	}

	/**
	 * 最小值
	 *
	 * @param key
	 * @return
	 */
	public static Aggr min(String key) {
		return new Aggr(key, MIN);
	}

	/**
	 * 合计
	 *
	 * @param key
	 * @return
	 */
	public static Aggr sum(String key) {
		return new Aggr(key, SUM);
	}

	/**
	 * 平均
	 *
	 * @param key
	 * @return
	 */
	public static Aggr avg(String key) {
		return new Aggr(key, AVG);
	}

	/**
	 * 第一个
	 *
	 * @param key
	 * @return
	 */
	public static Aggr first(String key) {
		return new Aggr(key, FIRST);
	}

	/**
	 * 最后一个
	 *
	 * @param key
	 * @return
	 */
	public static Aggr last(String key) {
		return new Aggr(key, LAST);
	}

	/**
	 * 最大值
	 *
	 * @param key
	 * @return
	 */
	public static Aggr max(Ele key) {
		return new Aggr(key, MAX);
	}

	/**
	 * 最小值
	 *
	 * @param key
	 * @return
	 */
	public static Aggr min(Ele key) {
		return new Aggr(key, MIN);
	}

	/**
	 * 求和
	 *
	 * @param key
	 * @return
	 */
	public static Aggr sum(Ele key) {
		return new Aggr(key, SUM);
	}

	/**
	 * 求平均
	 *
	 * @param key
	 * @return
	 */
	public static Aggr avg(Ele key) {
		return new Aggr(key, AVG);
	}

	/**
	 * 第一个
	 *
	 * @param key
	 * @return
	 */
	public static Aggr first(Ele key) {
		return new Aggr(key, FIRST);
	}

	public static Aggr count() {
		return sum(Value.of(1));
	}

	/**
	 * 最后一个
	 *
	 * @param key
	 * @return
	 */
	public static Aggr last(Ele key) {
		return new Aggr(key, LAST);
	}

	/**
	 * 根据传入的符号构建一个聚合函数
	 * @param symbol
	 * @param ele
	 * @return
	 */
	public static Ele ofSymbol(String symbol, Ele ele) {
		switch (symbol) {
			case "max":
				return max(ele);
			case "min":
				return min(ele);
			case "sum":
				return sum(ele);
			case "avg":
				return avg(ele);
			case "first":
				return first(ele);
			case "last":
				return last(ele);
			case "count":
				return sum(Value.of(1));
		}
		Aggr aggr = new Aggr();
		aggr.doc = new Document(symbol, ele.toExpression());
		return aggr;
	}

}
